package com.qf.controller;

import com.qf.utils.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.03.23
 * @since 1.0
 */
@RestController
public class SecondKillController {

    @Autowired
    private CuratorFramework cf;
    @Autowired
    RedisLockUtil redisLockUtil;
    //1.准备商品库
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2.准备全局商品数据
    public static Map<String,Integer> itemOrder = new HashMap<>();

    //3.初始化数据
    static{
        //一万件商品
        itemStock.put("牙刷",10000);
        //目前0订单
        itemOrder.put("牙刷",0);
    }

    /**
     * 秒杀下单
     * @return
     * @throws Exception
     */
    @GetMapping("/kill")
    public String kill(String item) throws Exception{

        //==========zookeeper实现分布式锁,加锁==========================
        //创建zookeeper锁对象,在zookeeper中创建一个临时有序节点,名称叫做/lock
        //InterProcessMutex lock = new InterProcessMutex(cf, "/lock");
        //if (lock.acquire( 1, TimeUnit.SECONDS)) {


        //==============redis实现分布式锁,加锁=========================
        if(redisLockUtil.lock(item,String.valueOf(System.currentTimeMillis()),1)){

            //1.扣减库存
            Integer stock = itemStock.get(item);
            if (stock <= 0) {
                return "商品库存不足！";
            }
            Thread.sleep(100);
            //扣减库存
            itemStock.put(item, stock - 1);

            //2.创建订单
            Thread.sleep(100);
            itemOrder.put(item, itemOrder.get(item) + 1);
            //zookeeper释放锁
            //lock.release();

            //========redis解锁=====
            redisLockUtil.unlock(item);

            //3.返回信息
            return "下单成功! item= " + itemStock.get(item) + ", order= " + itemOrder.get(item);
        }else{
            //当前不是最小节点，没有获取到锁
            return "不好意思没有抢到商品!";
        }

    }
}
